import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../widgets/platform/adaptive_card.dart';
import '../../widgets/platform/adaptive_text_field.dart';
import '../../widgets/platform/adaptive_button.dart';
import '../../../core/platform/platform_detector.dart';

/// 需求编辑页面
class RequirementEditPage extends ConsumerStatefulWidget {
  final int? requirementId; // 如果为null则是创建新需求，否则是编辑现有需求

  const RequirementEditPage({super.key, this.requirementId});

  @override
  ConsumerState<RequirementEditPage> createState() =>
      _RequirementEditPageState();
}

class _RequirementEditPageState extends ConsumerState<RequirementEditPage> {
  final _formKey = GlobalKey<FormState>();
  late TextEditingController _titleController;
  late TextEditingController _descriptionController;
  late TextEditingController _estimatedHoursController;

  String _priority = '中';
  String _status = '待办';
  String _project = '电商平台优化项目';
  String _assignee = '张三';

  @override
  void initState() {
    super.initState();
    _titleController = TextEditingController();
    _descriptionController = TextEditingController();
    _estimatedHoursController = TextEditingController();

    // 如果是编辑模式，加载现有需求数据
    if (widget.requirementId != null) {
      // TODO: 从数据库或API加载需求数据
      _loadRequirementData();
    }
  }

  void _loadRequirementData() {
    // 模拟加载数据
    _titleController.text = '用户登录功能';
    _descriptionController.text = '实现用户注册、登录和权限验证功能';
    _estimatedHoursController.text = '16';
    _priority = '高';
    _status = '进行中';
    _project = '电商平台优化项目';
    _assignee = '张三';
  }

  @override
  void dispose() {
    _titleController.dispose();
    _descriptionController.dispose();
    _estimatedHoursController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final isEditing = widget.requirementId != null;

    return Scaffold(
      appBar: AppBar(
        title: SelectableText(isEditing ? '编辑需求' : '创建需求'),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () => Navigator.of(context).pop(),
        ),
      ),
      body: Form(
        key: _formKey,
        child: SingleChildScrollView(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              AdaptiveCard(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    SelectableText(
                      isEditing ? '编辑需求信息' : '填写需求信息',
                      style: Theme.of(context).textTheme.titleLarge,
                    ),
                    const SizedBox(height: 16),

                    // 标题输入
                    AdaptiveTextField(
                      controller: _titleController,
                      labelText: '需求标题 *',
                      hintText: '请输入需求标题',
                      validator: (value) {
                        if (value == null || value.isEmpty) {
                          return '请输入需求标题';
                        }
                        return null;
                      },
                    ),
                    const SizedBox(height: 16),

                    // 描述输入
                    AdaptiveTextField(
                      controller: _descriptionController,
                      labelText: '需求描述',
                      hintText: '请输入需求详细描述',
                      maxLines: 3,
                    ),
                    const SizedBox(height: 16),

                    // 项目选择
                    _buildDropdownField(
                      context,
                      '所属项目',
                      _project,
                      ['电商平台优化项目', '移动应用开发', '数据分析平台'],
                      (value) => setState(() => _project = value!),
                    ),
                    const SizedBox(height: 16),

                    // 负责人选择
                    _buildDropdownField(
                      context,
                      '负责人',
                      _assignee,
                      ['张三', '李四', '王五', '赵六'],
                      (value) => setState(() => _assignee = value!),
                    ),
                    const SizedBox(height: 16),

                    // 优先级选择
                    _buildDropdownField(
                      context,
                      '优先级',
                      _priority,
                      ['高', '中', '低'],
                      (value) => setState(() => _priority = value!),
                    ),
                    const SizedBox(height: 16),

                    // 状态选择
                    _buildDropdownField(
                      context,
                      '状态',
                      _status,
                      ['待办', '进行中', '已完成', '阻塞'],
                      (value) => setState(() => _status = value!),
                    ),
                    const SizedBox(height: 16),

                    // 预估工时
                    AdaptiveTextField(
                      controller: _estimatedHoursController,
                      labelText: '预估工时(小时)',
                      hintText: '请输入预估工时',
                      keyboardType: TextInputType.number,
                    ),
                  ],
                ),
              ),

              const SizedBox(height: 24),

              // 操作按钮
              Row(
                children: [
                  Expanded(
                    child: AdaptiveButton(
                      isPrimary: false,
                      onPressed: () => Navigator.of(context).pop(),
                      child: const SelectableText('取消'),
                    ),
                  ),
                  const SizedBox(width: 16),
                  Expanded(
                    child: AdaptiveButton(
                      onPressed: _handleSave,
                      child: SelectableText(isEditing ? '更新' : '创建'),
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildDropdownField(
    BuildContext context,
    String label,
    String value,
    List<String> items,
    ValueChanged<String?> onChanged,
  ) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        SelectableText(
          label,
          style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                fontWeight: FontWeight.w500,
              ),
        ),
        const SizedBox(height: 8),
        DropdownButtonFormField<String>(
          initialValue: value,
          items: items.map((item) {
            return DropdownMenuItem(
              value: item,
              child: SelectableText(item),
            );
          }).toList(),
          onChanged: onChanged,
          decoration: InputDecoration(
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(8),
            ),
            contentPadding: PlatformDetector.getInputPadding(),
          ),
        ),
      ],
    );
  }

  void _handleSave() {
    if (_formKey.currentState!.validate()) {
      // TODO: 保存需求数据
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: SelectableText(
              widget.requirementId != null ? '需求更新成功' : '需求创建成功'),
        ),
      );

      // 返回上一页
      Navigator.of(context).pop();
    }
  }
}
